#include "dataaccessor.h"

#include <QSqlQuery>
#include <QSqlError>

DataAccessor::DataAccessor() {}

bool DataAccessor::createTables(QSqlDatabase db)
{
    QSqlQuery query(db);
    QString sql = "create table friend_applications ("
                  " id integer primary key,"
                  " applicant_id integer not null,"
                  " nickname text not null,"
                  " verify_info text not null,"
                  " create_time datetime not null,"
                  " alias text default null,"
                  " server_id integer not null unique,"
                  " status integer not null default 0);";
    query.prepare(sql);

    if (!query.exec()) {
        qCritical() << "Error creating 好友申请 table:" << query.lastError().text();
        return false;
    }

    // 创建第二张表， friend_list
    QString sql2 = "create  table friendship ("
                   " id integer primary key,"
                   " friend_id integer not null,"
                   " nickname text not null,"
                   " alias text not null,"
                   " create_time datetime not null,"
                   " status integer not null default 0);";

    query.prepare(sql2);
    if (!query.exec()) {
        qCritical() << "Error creating 好友 table:" << query.lastError().text();
        return false;
    }

    // 创建第三张表，chat_list
    QString sql3 = "create table chat_message ("
                   " id integer primary key,"
                   " friend_id integer not null,"
                   " chat_msg text not null,"
                   " create_time datetime not null,"
                   " is_send integer not null);";

    query.prepare(sql3);
    if (!query.exec()) {
        qCritical() << "Error creating 聊天记录 table:" << query.lastError().text();
        return false;
    }

    return true;
}

bool DataAccessor::insertNewFriendApplication(QSqlDatabase db, const int& applicantId,
                                       const QString& nickname, const QString& verifyInfo, const QDateTime& datetime,
                                       const int& serverId, const int& status)
{
    QSqlQuery query(db);
    QString sql = "insert into friend_applications ("
                  "applicant_id, nickname, verify_info, create_time, server_id, status)"
                  "values (:applicantId, :nickname, :verifyInfo, :createTime, :serverId, :status);";
    query.prepare(sql);
    query.bindValue(":applicantId", applicantId);
    query.bindValue(":nickname", nickname);
    query.bindValue(":verifyInfo", verifyInfo);
    query.bindValue(":createTime", datetime.toString(Qt::ISODate));
    query.bindValue(":serverId", serverId);
    query.bindValue(":status", status);


    if (!query.exec()) {
        qCritical() << "Error inserting data:" << query.lastError().text();
        return false;
    }
    return true;
}

bool DataAccessor::updateStatusById(QSqlDatabase db, const int& serverId,
                             const int& status, const QString& alias)
{
    QSqlQuery query(db);
    QString sql = "update friend_applications "
                  "set status = :status, alias = :alias "
                  "where server_id = :serverId; ";
    query.prepare(sql);
    query.bindValue(":status", status);
    query.bindValue(":alias", alias);
    query.bindValue(":serverId", serverId);


    if (!query.exec()) {
        qCritical() << "Error updating data:" << query.lastError().text();
        return false;
    }
    return true;
}

// 在好友申请表中，取出全部记录
bool DataAccessor::findAllFriendApplications(QSqlDatabase db, QVector<FriendApplication>& results)
{
    QSqlQuery query(db);
    QString sql = "select * from friend_applications;";
    query.prepare(sql);


    if (!query.exec()) {
        qCritical() << "Error find data:" << query.lastError().text();
        return false;
    }

    // 获取查询结果
    results.clear();
    while (query.next())
    {
        FriendApplication record;
        record.applicantId = query.value("applicant_id").toInt();
        record.nickname = query.value("nickname").toString();
        record.verifiyInfo = query.value("verify_info").toString();
        QString createTime = query.value("create_time").toString();
        record.createTime = QDateTime::fromString(createTime, Qt::ISODate);
        record.alias = query.value("alias").toString();
        record.serverId = query.value("server_id").toInt();
        record.status = query.value("status").toInt();
        results.append(record);
    }

    return true;
}

// 在好友关系表中，添加一条记录
bool DataAccessor::insertNewFriendship(QSqlDatabase db, const int& friendId,
        const QString& nickname, const QString& alias, const QDateTime& resultTime)
{
    QSqlQuery query(db);
    QString sql = " insert into friendship "
                  " (friend_id, nickname, alias, create_time) "
                  " values (:friendId, :nickname, :alias, :createTime);";
    query.prepare(sql);
    query.bindValue(":friendId", friendId);
    query.bindValue(":nickname", nickname);
    query.bindValue(":alias", alias);
    query.bindValue(":createTime", resultTime.toString(Qt::ISODate));


    if (!query.exec()) {
        qCritical() << "Error inserting data into friendship:" << query.lastError().text();
        return false;
    }
    return true;
}

// 在好友关系表中，取出所有好友
bool DataAccessor::findAllFriendships(QSqlDatabase db, QVector<Friendship>& results)
{
    QSqlQuery query(db);
    QString sql = "select * from friendship;";
    query.prepare(sql);


    if (!query.exec()) {
        qCritical() << "Error find data in friendship:" << query.lastError().text();
        return false;
    }

    // 获取查询结果
    results.clear();
    while (query.next())
    {
        Friendship record;
        record.friendId = query.value("friend_id").toInt();
        record.nickname = query.value("nickname").toString();
        record.alias = query.value("alias").toString();
        QString createTime = query.value("create_time").toString();
        record.createTime = QDateTime::fromString(createTime, Qt::ISODate);
        results.append(record);
    }

    return true;
}

// 在聊天消息表中，插入一条记录
bool DataAccessor::insertChatMsg(QSqlDatabase db, const int& friendId, const QString& chatMsg,
                          const QDateTime& datetime, const bool& isMeSend)
{
    QSqlQuery query(db);
    QString sql = " insert into chat_message "
                  " (friend_id, chat_msg, create_time, is_send) "
                  " values (:friendId, :chatMsg, :datetime, :isMeSend);";
    query.prepare(sql);
    query.bindValue(":friendId", friendId);
    query.bindValue(":chatMsg", chatMsg);
    query.bindValue(":datetime", datetime.toString(Qt::ISODate));
    query.bindValue(":isMeSend", isMeSend);


    if (!query.exec()) {
        qCritical() << "Error inserting data into chat_message:" << query.lastError().text();
        return false;
    }
    return true;
}

// 在聊天消息表中，根据friendId查询聊天记录
bool DataAccessor::findAllChatMsgByFriendId(QSqlDatabase db, const int& friendId,
                                     QVector<ChatMsgQuery>& results)
{
    qDebug() << friendId;
    QSqlQuery query(db);
    QString sql = "SELECT * "
                  " FROM chat_message "
                  " WHERE friend_id = :friendId "
                  " ORDER BY create_time ASC; ";
    query.prepare(sql);
    query.bindValue(":friendId", friendId);


    if (!query.exec()) {
        qCritical() << "Error find chat message:" << query.lastError().text();
        return false;
    }

    // 获取查询结果
    results.clear();
    while (query.next())
    {
        ChatMsgQuery record;
        record.friendId = query.value("friend_id").toInt();
        record.chatMsg = query.value("chat_msg").toString();
        QString createTime = query.value("create_time").toString();
        record.sendTime = QDateTime::fromString(createTime, Qt::ISODate);
        record.isMeSend = query.value("is_send").toBool();
        results.append(record);
    }

    return true;
}
